package JMSRaceServer.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import JMSRaceServer.RaceDO;

public class JMSRaceServerDAO implements IJMSRaceServerDAO
{
	Connection connection; 
    static final String controller = "org.sqlite.JDBC";
	
	public void connect() throws SQLException
	{
		try
		{
			Class.forName(controller);
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		connection = DriverManager.getConnection("jdbc:sqlite:db/jms-db/nafarroaraces.db");
	}

	public List<RaceDO> getRaces() throws SQLException 
	{
		List<RaceDO> races = null;
		try
		{
			races = new ArrayList<RaceDO>();
		 	Statement statement = this.connection.createStatement();  
         	ResultSet rs = statement.executeQuery("SELECT * FROM races;");  
         	while (rs.next()) 
         	{  
         		RaceDO race = new RaceDO(rs.getString("name"),rs.getFloat("distance"),rs.getString("date"),rs.getInt("places"));
        	 	races.add(race);
        	 }  
         	rs.close();
            statement.close();
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		return races;
	}

	public void disconnect() throws SQLException 
	{ 
       connection.close();  
	}
}
